
# 字典的定义

dic1 = {"name": "张三", "age": 18, "gender": "男"}      # 字典是无序的

dic2 = dict(
    [("name", "李四"), ("age", 19), ("gender", "女")]
)

print(dic1)


# 增加

dic1["class"] = "2301"      # 增加一个键值对

dic1.update({"hobbies": ["唱", "跳", "打篮球"]})

print(dic1)


# 查询, get 、 中括号

# print(
#     dic1.get('name'), "的兴趣爱好是: ", dic1["hobbies"]
# )

# print(
#     dic1.get('study_years')     # None
# )

# print(
#     dic1.get('study_years', 2.5)     # None
# )


# print(
#     dic1['study_years']     # 报错
# )


# 修改，与增加一样

dic1["class"] = "2302"      # 增加一个键值对

dic1.update({"hobbies": ["唱", "跳", "打篮球", "rap"]})

print(dic1)


# 删除

del dic1["gender"]

print(dic1)


age = dic1.pop("age")
print("年龄：", age)
print(dic1)


# 字典的遍历

# 遍历 keys

print("dic1 里的所有的键如下：")
for k in dic1.keys():
    print(k)


print()
# 遍历 values

print("dic1 里的所有的值如下：")
for v in dic1.values():
    print(v)


print()
# 遍历键值对

print("dic1 里的所有的键值对如下：")
for k, v in dic1.items():
    print(
        f"{k}: {v}"
    )

print()
print()
# 字典生成式

dic3 = {}
for i in range(10):
    if i % 2 == 0:
        dic3[i] = i * i     # i ** 2

print(dic3)


dic4 = {i: i**2 for i in range(10) if i % 2 != 0}
print(dic4)


# 成员判断

if "name" in dic1:
    print(f"字典 dic1 中有 name 键，对应的值为: {dic1.get('name')}")
else:
    print("字典 dic1 中没有 name 键")


print()
print()
print(f"dic4 是 {type(dic4)} 格式")

dic4 = str(dic4)        # 强制转换为字符串
print(f"经过 str 转换后，dic4 是 {type(dic4)} 格式")
print(dic4)
